import { useCallback, useMemo, useState } from "react";
import { Form, Button, AutoCenter } from 'antd-mobile';
import { PlayOutline, FileOutline, DownCircleOutline } from 'antd-mobile-icons';
import { SubTitle } from '../components/SubTitle';
import { QA } from './QA';
import { useSelector, useDispatch } from 'react-redux';
import { setQAs, setExplain0, setExplain1, setExplain2, fetchAnalysis } from '../slices/questionsSlice';

function generateDecreaseValueAtIndex(index) {
  if (index < 0 || index > 9) {
    return "请输入0到9之间的数字。";
  }

  let decreaseValue = 0; // 这个变量用于存储递减的值

  let slowDecrementCount = Math.floor(Math.random() * 3) + 2;
  let fastDecrementCount = Math.floor(Math.random() * 2) + 1;

  if (index === 0) {
    return 0;  // 第一个数没有递减
  }

  if (index <= slowDecrementCount) {
    decreaseValue = Math.random() * 2; // 递减幅度较慢
  } else if (index <= slowDecrementCount + (10 - slowDecrementCount - fastDecrementCount)) {
    decreaseValue = (Math.random() * 3) + 2; // 中间递减幅度
  } else {
    decreaseValue = (Math.random() * 5) + 5; // 递减幅度较快
  }

  return decreaseValue;
}

function generateDecreasingArray(length) {
  if (length <= 0) return [];

  let numbers = new Set();

  // Generate unique random numbers
  while (numbers.size < length) {
    numbers.add(Math.round((Math.random() * 11) * 1000) / 1000); // Random number between 0 and 10
  }

  // Convert Set to Array and sort in decreasing order
  return [...numbers].sort((a, b) => b - a);
}

export function QAs() {
  const dispatch = useDispatch();
  const [waittingAnalysis, setWaittingAnalysis] = useState(false);
  const qas = useSelector(state => state.questions.present.qas);
  const currQ = useSelector(state => state.questions.present.currQ);
  const nextQA = useMemo(() => qas && qas.findIndex(qa => !qa.show), [qas]);
  const handleButtonClick = useCallback(async () => {
    if (nextQA !== -1) {
      dispatch(setQAs(qas.map((qa, i) => {
        if (nextQA === i) {
          return { ...qa, show: true };
        }
        return { ...qa };
      })));
    } else {
      setWaittingAnalysis(true);
      await dispatch(fetchAnalysis({ qas, q: currQ?.question }));
      setWaittingAnalysis(false);
    }
  }, [qas, nextQA, dispatch, currQ?.question]);

  return (
    qas &&
    <>
      <SubTitle
        icon={<FileOutline />}
        title="我想知道 "
        stitle="您的一些情况。"
        detail="尝试回答您的情况。"
        speed={10} />
      <Form style={{ marginTop: '8px' }}>
        {qas.map((qa, index) => (
          (qa.show) && <QA key={index} qa={qa} onChange={(value, isMove = false) => {
            if (qa.type === 0) {
              value = value.map((s, i) => {
                let score;
                if (s.score && !isMove) {
                  score = s.score
                } else {
                  score = 99;
                  if (qa.answer && qa.answer.length > 0) {
                    if (qa.answer[i] && qa.answer[i].score) {
                      score = qa.answer[i].score;
                    } else {
                      score = Math.floor(qa.answer[i - 1].score - generateDecreaseValueAtIndex(i));
                    }
                  }
                }
                return { ...s, score: score < 0 ? 0 : score }
              });
              value = value.sort((v1, v2) => v2.score - v1.score);
              dispatch(setExplain0(undefined));
            }
            if (qa.type === 1) {
              const arr = generateDecreasingArray(value.length);
              value = value.map((w, i) => ({ ...w, score: arr[i] }));
              dispatch(setExplain1(undefined));
            }
            if (qa.type === 2) {
              dispatch(setExplain2(undefined));
            }
            dispatch(setQAs(qas.map(qa_ => {
              if (qa_.id === qa.id) {
                if (qa.type === 2) {
                  return { ...qa_, answer: value, answer_after_analysis: undefined };
                }
                return { ...qa_, answer: value };
              } else {
                return qa_;
              }
            })));
          }} />
        ))}
        <AutoCenter>
          <Button loading={waittingAnalysis} fill='none' onClick={handleButtonClick} style={{ color: "rgb(25, 85, 110)" }}>
            {nextQA !== -1 ? (<div><DownCircleOutline />&nbsp;继续</div>) : <div className="qas-analysis"><PlayOutline />&nbsp;分析</div>}
          </Button>
        </AutoCenter>
      </Form>
    </>
  );
}
